package com.example.jetpackdemo.viewmodel

import android.text.Editable
import android.util.JsonReader
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.example.jetpackdemo.common.BaseApplication
import com.example.jetpackdemo.common.listener.SimpleWatcher
import com.example.jetpackdemo.db.data.Shoe
import com.example.jetpackdemo.db.data.User
import com.example.jetpackdemo.db.repository.UserRepository
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

class LoginModel constructor(private val repository: UserRepository) : ViewModel() {
    val n = MutableLiveData("")
    val p = MutableLiveData("")
    val enable = MutableLiveData(false)

    /**
     * 用户名改变的回调
     */
    fun onNameChanged(s: CharSequence) {
        n.value = s.toString()
        judgeEnable()
    }

    private fun judgeEnable() {
        enable.value = n.value!!.isNotEmpty() && p.value!!.isNotEmpty()
    }

    /**
     * 密码改变的回调
     */
    fun onPwdChanged(s: CharSequence, start: Int, before: Int, count: Int) {
        p.value = s.toString()
        judgeEnable()
    }

    //SimpleWatcher 是简化了的TextWatcher
    val nameWatcher = object : SimpleWatcher() {
        override fun afterTextChanged(s: Editable?) {
            super.afterTextChanged(s)
            n.value = s.toString()
            judgeEnable()
        }
    }

    val pwdWatcher = object : SimpleWatcher() {
        override fun afterTextChanged(s: Editable?) {
            super.afterTextChanged(s)
            p.value = s.toString()
            judgeEnable()
        }
    }

    fun login(): LiveData<User?>? {
        val pwd = p.value!!
        val account = n.value!!
        return repository.login(account, pwd)
    }


    /**
     * 第一次启动的时候调用
     */

    fun onFirstLauch(): String {
        val context = BaseApplication.context
        context.assets.open("shoes.json").use {
            JsonReader(it.reader()).use {
                val shoeType = object : TypeToken<List<Shoe>>() {}.type
//                val shoeList: List<Shoe> = Gson().fromJson(it,shoeType)
            }
        }
        return ""
    }


}